<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Models\FunctionModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MenuAdminController extends Controller
{
    /**
     * 获取菜单列表
     */
    public function index(Request $request)
    {
        try {
            $query = Menu::with(['functions' => function ($query) {
                $query->orderBy('sort_order');
            }]);

            // 搜索
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
                });
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $menus = $query->orderBy('sort_order')->paginate($perPage);

            return $this->paginate($menus, '获取菜单列表成功');
        } catch (\Exception $e) {
            return $this->error('获取菜单列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建菜单
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:100|unique:menus',
                'name' => 'required|string|max:100',
                'icon' => 'nullable|string|max:50',
                'path' => 'nullable|string|max:200',
                'component' => 'nullable|string|max:100',
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
                'is_visible' => 'boolean',
                'sort_order' => 'integer|min:0',
            ]);

            $menu = Menu::create($data);

            return $this->success($menu->load('functions'), '创建菜单成功', 201);
        } catch (\Exception $e) {
            return $this->error('创建菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取菜单详情
     */
    public function show(Menu $menu)
    {
        try {
            return $this->success($menu->load(['functions' => function ($query) {
                $query->with('permissionNodes')->orderBy('sort_order');
            }]), '获取菜单详情成功');
        } catch (\Exception $e) {
            return $this->error('获取菜单详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新菜单
     */
    public function update(Request $request, Menu $menu)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:100|unique:menus,code,' . $menu->id,
                'name' => 'required|string|max:100',
                'icon' => 'nullable|string|max:50',
                'path' => 'nullable|string|max:200',
                'component' => 'nullable|string|max:100',
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
                'is_visible' => 'boolean',
                'sort_order' => 'integer|min:0',
            ]);

            $menu->update($data);

            return $this->success($menu->load('functions'), '更新菜单成功');
        } catch (\Exception $e) {
            return $this->error('更新菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除菜单
     */
    public function destroy(Menu $menu)
    {
        try {
            // 检查是否有功能关联
            if ($menu->functions()->count() > 0) {
                return $this->error('无法删除包含功能的菜单', 422);
            }

            $menu->delete();

            return $this->success(null, '删除菜单成功');
        } catch (\Exception $e) {
            return $this->error('删除菜单失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取菜单的功能列表
     */
    public function getFunctions(Menu $menu)
    {
        try {
            $functions = $menu->functions()
                ->with('permissionNodes')
                ->orderBy('level')
                ->orderBy('sort_order')
                ->get();

            return $this->success($functions, '获取功能列表成功');
        } catch (\Exception $e) {
            return $this->error('获取功能列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 为菜单添加功能
     */
    public function addFunction(Request $request, Menu $menu)
    {
        try {
            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:100|unique:functions',
                'name' => 'required|string|max:100',
                'level' => 'required|in:core,optional',
                'description' => 'nullable|string|max:500',
                'dependencies' => 'array',
                'dependencies.*' => 'integer|exists:functions,id',
                'permission_nodes' => 'array',
                'permission_nodes.*' => 'integer|exists:permission_nodes,id',
                'sort_order' => 'integer|min:0',
            ]);

            // 创建功能
            $function = $menu->functions()->create([
                'code' => $data['code'],
                'name' => $data['name'],
                'level' => $data['level'],
                'description' => $data['description'] ?? null,
                'dependencies' => $data['dependencies'] ?? [],
                'sort_order' => $data['sort_order'] ?? 0,
            ]);

            // 关联权限节点
            if (!empty($data['permission_nodes'])) {
                $function->permissionNodes()->attach($data['permission_nodes']);
            }

            return $this->success($function->load('permissionNodes'), '添加功能成功', 201);
        } catch (\Exception $e) {
            return $this->error('添加功能失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新菜单功能
     */
    public function updateFunction(Request $request, Menu $menu, FunctionModel $function)
    {
        try {
            // 确保功能属于该菜单
            if ($function->menu_id !== $menu->id) {
                return $this->error('功能不属于该菜单', 404);
            }

            $data = $this->validateRequest($request, [
                'code' => 'required|string|max:100|unique:functions,code,' . $function->id,
                'name' => 'required|string|max:100',
                'level' => 'required|in:core,optional',
                'description' => 'nullable|string|max:500',
                'dependencies' => 'array',
                'dependencies.*' => 'integer|exists:functions,id',
                'permission_nodes' => 'array',
                'permission_nodes.*' => 'integer|exists:permission_nodes,id',
                'sort_order' => 'integer|min:0',
            ]);

            // 更新功能
            $function->update([
                'code' => $data['code'],
                'name' => $data['name'],
                'level' => $data['level'],
                'description' => $data['description'] ?? null,
                'dependencies' => $data['dependencies'] ?? [],
                'sort_order' => $data['sort_order'] ?? 0,
            ]);

            // 更新权限节点关联
            if (isset($data['permission_nodes'])) {
                $function->permissionNodes()->sync($data['permission_nodes']);
            }

            return $this->success($function->load('permissionNodes'), '更新功能成功');
        } catch (\Exception $e) {
            return $this->error('更新功能失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除菜单功能
     */
    public function removeFunction(Menu $menu, FunctionModel $function)
    {
        try {
            // 确保功能属于该菜单
            if ($function->menu_id !== $menu->id) {
                return $this->error('功能不属于该菜单', 404);
            }

            // 检查是否有角色在使用此功能
            if ($function->roles()->count() > 0) {
                return $this->error('无法删除正在使用的功能', 422);
            }

            $function->delete();

            return $this->success(null, '删除功能成功');
        } catch (\Exception $e) {
            return $this->error('删除功能失败: ' . $e->getMessage());
        }
    }
}
